package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import entity.ComplaintUpgrade;
import enum_var.ComplaintStatus;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import service.ComplaintService;
import service.impl.ComplaintServiceImpl;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/api/complaint/*")
public class ComplaintServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final ComplaintService complaintService = new ComplaintServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (pathInfo == null || "/".equals(pathInfo)) {
                // 获取投诉列表
                if ("CONSUMER".equals(role)) {
                    // 消费者只能查看自己的投诉
                    List<ComplaintUpgrade> complaints = complaintService.getComplaintsByUserId(userId);
                    result.put("success", true);
                    result.put("data", complaints);
                } else if ("CUSTOMER_SERVICE".equals(role)) {
                    // 客服查看所有投诉
                    String status = request.getParameter("status");
                    List<ComplaintUpgrade> complaints;
                    if (status != null) {
                        complaints = complaintService.getComplaintsByStatus(ComplaintStatus.valueOf(status));
                    } else {
                        complaints = complaintService.getAllComplaints();
                    }
                    result.put("success", true);
                    result.put("data", complaints);
                } else {
                    throw new Exception("权限不足");
                }
            } else if (pathInfo.startsWith("/detail/")) {
                // 获取投诉详情
                Long complaintId = Long.parseLong(pathInfo.substring(8));
                ComplaintUpgrade complaint = complaintService.getComplaintById(complaintId);
                
                if (complaint == null) {
                    throw new Exception("投诉不存在");
                }
                
                // 权限检查
                if ("CONSUMER".equals(role) && !complaint.getUserId().equals(userId)) {
                    throw new Exception("权限不足");
                }
                
                result.put("success", true);
                result.put("data", complaint);
            } else {
                throw new Exception("无效的请求路径");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (!"CONSUMER".equals(role)) {
                throw new Exception("只有消费者可以提交投诉");
            }

            // 解析请求参数
            Long applicationId = Long.parseLong(request.getParameter("applicationId"));
            String complaintReason = request.getParameter("complaintReason");
            String evidenceUrls = request.getParameter("evidenceUrls");

            // 创建投诉
            ComplaintUpgrade complaint = new ComplaintUpgrade();
            complaint.setUserId(userId);
            complaint.setApplicationId(applicationId);
            complaint.setComplaintReason(complaintReason);
            complaint.setEvidenceUrls(evidenceUrls);
            complaint.setStatus(ComplaintStatus.PENDING);
            complaint.setCreateTime(LocalDateTime.now());

            // 保存投诉
            complaintService.createComplaint(complaint);

            result.put("success", true);
            result.put("message", "投诉提交成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (!"CUSTOMER_SERVICE".equals(role)) {
                throw new Exception("只有客服可以处理投诉");
            }

            if (pathInfo == null || !pathInfo.startsWith("/handle/")) {
                throw new Exception("无效的请求路径");
            }

            Long complaintId = Long.parseLong(pathInfo.substring(8));
            String action = request.getParameter("action"); // process, resolve
            String handleResult = request.getParameter("handleResult");

            ComplaintUpgrade complaint = complaintService.getComplaintById(complaintId);
            if (complaint == null) {
                throw new Exception("投诉不存在");
            }

            if ("process".equals(action)) {
                complaint.setStatus(ComplaintStatus.PROCESSING);
                complaint.setHandleTime(LocalDateTime.now());
                complaint.setHandleResult(handleResult);
            } else if ("resolve".equals(action)) {
                complaint.setStatus(ComplaintStatus.RESOLVED);
                complaint.setHandleTime(LocalDateTime.now());
                complaint.setHandleResult(handleResult);
            } else {
                throw new Exception("无效的操作");
            }

            complaintService.updateComplaint(complaint);

            result.put("success", true);
            result.put("message", "处理成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (pathInfo == null || !pathInfo.startsWith("/cancel/")) {
                throw new Exception("无效的请求路径");
            }

            Long complaintId = Long.parseLong(pathInfo.substring(8));
            ComplaintUpgrade complaint = complaintService.getComplaintById(complaintId);

            if (complaint == null) {
                throw new Exception("投诉不存在");
            }

            // 只有投诉人和客服可以取消投诉
            if (!complaint.getUserId().equals(userId) && !"CUSTOMER_SERVICE".equals(role)) {
                throw new Exception("权限不足");
            }

            // 只有待处理状态的投诉可以取消
            if (complaint.getStatus() != ComplaintStatus.PENDING) {
                throw new Exception("只能取消待处理的投诉");
            }

            complaintService.deleteComplaint(complaintId);

            result.put("success", true);
            result.put("message", "投诉已取消");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }
}
